/**
 * 
 */
package br.com.ufrn.aipetro.ga.model.persist.hibernate.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author Lucas
 * @author Andre
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static {
        try {
        	// Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
        	Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static Session beginTransaction() {
    	Session session = getSessionFactory().getCurrentSession();
    	if (!session.getTransaction().isActive())
    		getSessionFactory().getCurrentSession().beginTransaction();
    	
    	return session;
    }
    
    public static void commitTransaction() {
    	Session session = getSessionFactory().getCurrentSession();
    	if (session.getTransaction().isActive())
    		getSessionFactory().getCurrentSession().getTransaction().commit();
    }
}
